import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
  NotFoundException,
  UseGuards,
  Request,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiParam,
} from '@nestjs/swagger';
import { TodoService } from './todo.service';
import { CreateTodoDto } from './dto/create-todo.dto';
import { UpdateTodoDto } from './dto/update-todo.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';

@ApiTags('todos')
@ApiBearerAuth('JWT-auth')
@Controller('todos')
@UseGuards(JwtAuthGuard)
export class TodoController {
  constructor(private readonly todoService: TodoService) {}

  @Get()
  @ApiOperation({
    summary: '获取所有任务',
    description: '获取当前用户的所有主任务列表（包含子任务）',
  })
  @ApiResponse({ status: 200, description: '成功获取任务列表' })
  @ApiResponse({ status: 401, description: '未授权，需要登录' })
  findAll() {
    return this.todoService.findAll();
  }

  @Get(':id')
  @ApiOperation({
    summary: '获取单个任务',
    description: '根据 ID 获取任务详情',
  })
  @ApiParam({ name: 'id', description: '任务 ID', example: 1 })
  @ApiResponse({ status: 200, description: '成功获取任务' })
  @ApiResponse({ status: 404, description: '任务不存在' })
  @ApiResponse({ status: 401, description: '未授权' })
  findOne(@Param('id') id: string) {
    const todo = this.todoService.findOne(+id);
    if (!todo) {
      throw new NotFoundException(`Todo with ID ${id} not found`);
    }
    return todo;
  }

  @Post()
  @ApiOperation({ summary: '创建任务', description: '创建新的任务或子任务' })
  @ApiResponse({ status: 201, description: '任务创建成功' })
  @ApiResponse({ status: 400, description: '请求参数错误' })
  @ApiResponse({ status: 401, description: '未授权' })
  create(@Body() createTodoDto: CreateTodoDto, @Request() req) {
    console.log('当前登录用户信息:', req.user);

    // 如果没有传 creatorId，使用当前登录用户
    if (!createTodoDto.creatorId) {
      createTodoDto.creatorId = req.user.id;
    }
    // 如果没有传 assigneeId，默认设置为创建者
    if (!createTodoDto.assigneeId) {
      createTodoDto.assigneeId = createTodoDto.creatorId;
    }

    console.log('接收到的创建任务数据:', createTodoDto);

    return this.todoService.create(createTodoDto);
  }

  @Patch(':id')
  @ApiOperation({
    summary: '更新任务',
    description: '更新任务信息（标题、完成状态、负责人等）',
  })
  @ApiParam({ name: 'id', description: '任务 ID', example: 1 })
  @ApiResponse({ status: 200, description: '任务更新成功' })
  @ApiResponse({ status: 404, description: '任务不存在' })
  @ApiResponse({ status: 401, description: '未授权' })
  update(@Param('id') id: string, @Body() updateTodoDto: UpdateTodoDto) {
    const todo = this.todoService.update(+id, updateTodoDto);
    if (!todo) {
      throw new NotFoundException(`Todo with ID ${id} not found`);
    }
    return todo;
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除任务', description: '删除指定任务' })
  @ApiParam({ name: 'id', description: '任务 ID', example: 1 })
  @ApiResponse({ status: 200, description: '任务删除成功' })
  @ApiResponse({ status: 404, description: '任务不存在' })
  @ApiResponse({ status: 401, description: '未授权' })
  async remove(@Param('id') id: string) {
    await this.todoService.remove(+id);
    return { message: 'Todo deleted successfully' };
  }
}
